<template>
  <div>
    <el-form :model="formData" :rules="rules">
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="password2">
        <el-input v-model="formData.password2" />
      </el-form-item>
      <el-button>注册</el-button>
    </el-form>
  </div>
</template>

<script>

export default {
  data() {
    // 自定义校验函数
    const checkPassword = (rule, val, callback) => {
      // 每当触发校验, 这个函数就会被触发
      // 自动传入 三个参数
      // rule 当前规则
      // val 当前输入值
      // callback 放行回调
      // 1. 写逻辑判断val是否合法, 给出布尔值
      const isSamePass = val === this.formData.password
      // 2. 根据 element ui 的需求调用回调放行或者显示报错
      if (isSamePass) {
        // 成功
        callback()
      } else {
        // 失败
        // 需要在回调中带上一个原生错误对象 new Error('xxx')
        callback(new Error('两次密码必须相同'))
      }
    }

    return {
      formData: {
        mobile: '',
        password: '',
        password2: ''
      },
      rules: {
        mobile: [
          { required: true, message: '请填写信息', trigger: 'blur' },
          { pattern: /^1[3-9][0-9]{9}$/, message: '请输入正确手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请填写信息', trigger: 'blur' },
          { min: 6, max: 12, message: '请输入6-12位密码', trigger: 'blur' }
        ],
        password2: [
          { required: true, message: '请填写信息', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ]
      }
    }
  }
}
</script>

<style>

</style>
